<template>
  <div class="app-container" style="height: ;">
    <div style="width: 100%; height: 50px; margin: 0 auto; text-align: center;">
      <span style="font-size: 27px;">会员入会</span>
    </div>

    <div style="width: 90%; height: 50px; background-color: #717685; margin: 0 auto; border-radius: 10px;"></div>

    <div style="width: 100%; height: 30px;"></div>

    <!-- 会员入会的输入框 -->
    <div
      style="width: 90%; height: 700px; margin: 0 auto; background-color: white; border: 0.5px solid #ccc; border-radius: 10px; padding: 20px;">
      <div style="width: 100%; height: 20px;"></div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div style="width: 75%;float: left;">
          <el-row>
            <el-col :span="12">
              <el-form-item label="姓名" prop="memberUserRealName">
                <el-input v-model="form.memberUserRealName" placeholder="请输入姓名" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="memberUserPhone">
                <el-input v-model="form.memberUserPhone" placeholder="请输入手机号" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-upload style="float: right; width: 180px; margin-top: -57px;" action="123123123" list-type="picture-card" class="upload-demo" :show-file-list="false" :before-upload="beforeAvatarUpload">
                      <img height="148" v-if="images" :src="images" class="avatar" />
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                     -->
          <!--  -->
          <el-row style="margin-top: 15px;">
            <el-col :span="12">
              <el-form-item label="性别" prop="memberUserSex">
                <el-radio v-model="form.memberUserSex" label="0">男</el-radio>
                <el-radio v-model="form.memberUserSex" label="1">女</el-radio>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="年龄" prop="resememberUserAgervation">
                <el-input type="number" v-model="form.memberUserAge" placeholder="请输入年龄" maxlength="50" />
              </el-form-item>
            </el-col>
          </el-row>
          <!--  -->
          <el-row>
            <el-col :span="12">
              <el-form-item label="会员卡号" prop="membershipCardNumber">
                <el-input v-model="form.membershipCardNumber" placeholder="请输入会员卡号" maxlength="50" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="卡名称" prop="memberTypeId">
                <el-select v-model="form.memberTypeId" placeholder="请输入会员卡名称" style="width: 100%;">
                  <el-option v-for="item in memberList" :key="item.id" :label="item.memberTypeName" :value="item.id"
                    @click="handleStatusChange(item.memberType)"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="statusChange && form.memberTypeId">
            <el-col :span="12">
              <el-form-item label="可用次数" prop="availableTimes">
                <el-input v-model="form.availableTimes" placeholder="请输入会员卡可用次数"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row v-if="!statusChange && form.memberTypeId">
            <el-col :span="12">
              <el-form-item label="有效期限" prop="serviceLife">
                <el-input v-model="form.serviceLife" placeholder="请输入会员卡有效期限"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <!--  -->
          <el-row style="margin-top: 15px;">
            <el-col :span="18">
              <el-form-item label="备注">
                <el-input v-model="form.description" type="textarea" placeholder="请输入内容" :rows="5"
                  :resize="'none'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div style="width: 25%;float: left;">
          <el-form-item label="用户照片" prop="memberUserPhoto" style="margin-left: 10%;">
            <el-button type="primary" @click="openCamera">打开摄像头拍照</el-button>
            <br>
            <el-dialog :visible.sync="showCameraDialog" width="600px">
              <video width="550px" ref="video" autoplay></video>
              <canvas ref="canvas" style="display: none;"></canvas>
              <br>
              <el-button type="primary" @click="takePhoto">拍照</el-button>
            </el-dialog>

          </el-form-item>
          <img style="width: 80%;margin-top: 10px;margin-left: 10%;" v-if="memberUserPhoto1" :src="memberUserPhoto1"
            class="avatar" />
        </div>
        <div style="display: flex;width: 100%;">
          <div
            style="height: 40px; width: 150px; display: flex; margin-left: 42%; margin-top: 15%; align-items: center; justify-content: center; text-align: center; background-color: #1A6290; border-radius: 10px;">
            <span style="font-size: 18px; color: rgba(255, 255, 255, 0.938);" @click="submitForm">保存</span>
          </div>

          <div
            style="height: 40px; width: 200px; display: flex; margin-left: 1%; margin-top: 15%; align-items: center; justify-content: center; text-align: center; background-color: #1A6290; border-radius: 10px;">
            <span style="font-size: 18px; color: rgba(255, 255, 255, 0.938);" @click="readCard">录入会员卡</span>
          </div>
        </div>

      </el-form>
    </div>


  </div>
</template>
<script>
import { getMemberType, getById, addMember, updateMemberById, getMemberLists, selectUserInfoByNumid } from "@/api/memberUser/index";
import { } from "@/api/trainingTime/index.js"; // 导入时间接口
import { list } from "@/api/monitor/logininfor";
import { param } from "@/utils";
import moment from 'moment';
import { formToJSON } from "axios";

export default {
  name: 'Course',
  data() {
    return {
      // 下拉框状态
      statusChange: '',
      // 会员下拉框数据
      memberList: [],
      //添加时赋值
      addimages: "",
      // 图片回显
      memberUserPhoto1: "",
      // 租户标识
      venueUniqueIdentifier: '',
      // 拍照弹出框
      showCameraDialog: false,
      radio: '1',
      // 课程数据
      tableData: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        memberType: '',
        membershipCardNumber: ''
      },
      // 课程查询条件
      queryForm: {},
      // 表单验证规则
      rules: {
        memberUserRealName: [{ required: true, message: "请输入会员用户名称", trigger: "blur" },
        { max: 25, message: '最大字符为25', trigger: 'blur' }],
        memberTypeName: [
          { required: true, message: "请输入类型名称", trigger: "blur" },
        ],
        memberUserSex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        memberUserAge: [{ required: true, message: "请输入年龄", trigger: "blur" },
        {
          validator: (rule, value, callback) => {
            const age = parseInt(value);
            if (Number.isInteger(age) && age > 0) {
              callback();
            } else {
              callback(new Error('年龄必须为正整数'));
            }
          },
          trigger: "blur"
        }],
        memberUserPhone: [{ validator: this.validatorPhone, trigger: "blur" }],
        memberTypeId: [{ required: true, message: "请选择开通会员类型", trigger: "blur" }],
        availableTimes: [
          { required: true, message: "请输入次数", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const times = parseInt(value);
              if (Number.isInteger(times) && times > 0) {
                callback();
              } else {
                callback(new Error('次数必须为正整数'));
              }
            },
            trigger: "blur"
          }
        ],
        serviceLife: [
          { required: true, message: "请输入期限值", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              const life = parseInt(value);
              if (Number.isInteger(life) && life > 0) {
                callback();
              } else {
                callback(new Error('期限值必须为正整数'));
              }
            },
            trigger: "blur"
          }
        ]
      },

    }
  },
  watch: {
    // 监听下拉框是否变化
    'form.memberTypeId': function (newVal) {
      console.log(newVal)
      const selectedItem = this.memberList.find(item => item.id === newVal);
      if (selectedItem) {
        this.handleStatusChange(selectedItem.memberType);
      }
    },
  },
  created() {
    this.venueUniqueIdentifier = sessionStorage.getItem('venueUniqueIdentifier');
    this.getMemberList()
  },
  methods: {
    beforeDestroy() {
      // 在页面销毁时关闭 WebSocket 连接
      this.ws.close();
    },
    // 读取会员卡卡号
    readCard() {
      var self = this; // 保存 Vue 实例的引用
      // 创建 WebSocket 对象并指定连接地址
      var ws = new WebSocket('ws://localhost:12222/ws');

      // 监听 WebSocket 连接打开事件
      ws.onopen = function (event) {
        console.log('WebSocket连接已经打开');
        // 在连接打开后可以执行的操作
      };

      // 监听 WebSocket 接收消息事件
      ws.onmessage = function (event) {
        if (event) {
          console.log(event)
          
          const parsedMessage = JSON.parse(event.data);
          const { customValue, readResult } = parsedMessage;
          self.form.membershipCardNumber = readResult
        }
        console.log('接收到消息: ' + event.data);

        // 处理接收到的消息
      };

      // 监听 WebSocket 连接关闭事件
      ws.onclose = function (event) {
        console.log('WebSocket连接已经关闭');
        // 在连接关闭后可以执行的操作
      };

      // 监听 WebSocket 连接错误事件
      ws.onerror = function (event) {
        console.error('WebSocket连接发生错误');
        // 处理连接错误
      };
    },
    // 保存
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const formData = new FormData();
          if (this.form.memberUserHeight === undefined || this.form.memberUserHeight === null) {
            this.form.memberUserHeight = 0
          }
          if (this.form.memberUserWeight === undefined || this.form.memberUserWeight === null) {
            this.form.memberUserWeight = 0.00
          }
          // 校验通过，执行添加修改操作
          for (const key in this.form) {
            formData.set(key, this.form[key]);
            formData.get(key);
          }
          if (this.form.memberUserPhoto === "" || this.form.memberUserPhoto === null || this.form.memberUserPhoto === undefined) {
            formData.set("memberUserPhoto", 0);
          }
          if (this.form.serviceLife === "" || this.form.serviceLife === null || this.form.serviceLife === undefined) {
            formData.set("serviceLife", 0)
          }
          if (this.addimages) {
            formData.set("file", this.addimages, this.addimages.name);
          } else { }
          formData.set("venueUniqueIdentifier", this.venueUniqueIdentifier)
          // 将memberType添加到formData中
          formData.set('memberType', this.form.memberType);
          addMember(formData)
            .then((res) => {
              if (res.data.data === "SAVE_OK") {
                this.$message({ type: "success", message: "添加成功" });
                this.memberUserPhoto1 = ""
                this.addimages = ""
                this.$router.push('/member/memberUserManagerment') 
              } else if (res.data.data === "FILE_EMPTY") {
                this.$message.error({ type: "warning", message: "图片不能为空" });
              } else if (res.data.data === "手机号已存在") {
                this.$message.error({ type: "warning", message: "手机号已存在" });
              } else if (res.data.data === "存在空内容") {
                this.$message.error({ type: "warning", message: "存在空内容" });
              } else if (res.data.data === "SAVE_ERROR") {
                this.$message.error({ type: "warning", message: "添加失败" });
              }
            }).catch((error) => {
              console.log(error)
            });
        }
      })
    },
    // 新增按钮操作
    handleAdd() {
      // 清除表单数据
      if (this.$refs.form !== undefined) {
        this.$refs.form.resetFields();
      }
      this.form = {
        membershipCardNumber: '',
        memberUserPhoto: ''
      }
      this.title = "添加会员类型";
      this.memberUserPhoto1 = ""
      this.addimages = ""
      this.form.memberType = '';

    },
    // 判断下拉框
    handleStatusChange(memberType) {
      this.statusChange = memberType === 0;
      this.form.memberType = memberType
    },
    // 会员类型下拉框选项
    getMemberList() {
      getMemberLists(this.venueUniqueIdentifier).then((res) => {
        this.memberList = res.data.data
      })
    },
    // 打开摄像头
    openCamera() {
      this.showCameraDialog = true;
      navigator.mediaDevices.getUserMedia({ video: true })
        .then((stream) => {
          const video = this.$refs.video;
          video.srcObject = stream;
          video.play();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 拍照并调用方法处理
    takePhoto() {
      const canvas = this.$refs.canvas;
      const context = canvas.getContext('2d');
      const video = this.$refs.video;
      canvas.width = video.videoWidth;
      canvas.height = video.videoHeight;
      context.drawImage(video, 0, 0, canvas.width, canvas.height);
      const dataURL = canvas.toDataURL('image/jpeg');

      // 创建一个Blob对象来代表照片文件
      const blob = this.dataURLtoBlob(dataURL);
      blob.lastModifiedDate = new Date();
      blob.name = 'photo.jpg';

      this.beforeAvatarUpload(blob);
      this.showCameraDialog = false;
    },
    // 对拍到的照片进行处理
    dataURLtoBlob(dataURL) {
      const byteString = atob(dataURL.split(',')[1]);
      const mimeString = dataURL.split(',')[0].split(':')[1].split(';')[0];
      const ab = new ArrayBuffer(byteString.length);
      const ia = new Uint8Array(ab);
      for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ab], { type: mimeString });
    },
    handleMembershipCardNumberChanged(newValue) {
      if (this.memberopen === true && this.form.id === undefined) {
        this.form.membershipCardNumber = newValue
      }
    },
    // 文件上传校验
    beforeAvatarUpload(file) {
      //上传图片格式
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是JPG/PNG格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过2MB!");
        return false;
      }
      //赋值
      this.addimages = file;
      this.memberUserPhoto1 = URL.createObjectURL(file);
      //isJPG && isLt2M 自动提交 false 是点击确定后提交
      return false;
    },
    // 验证手机号格式，其他用户是否绑定
    validatorPhone(memberUserPhone, value, callback) {
      // 验证手机号的正则表达式
      const reg = /^(((13[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[3-8]{1})|(18[0-9]{1})|(19[0-9]{1})|(14[5-7]{1}))+\d{8})$/
      if (value !== '') {
        if (!reg.test(value)) {
          callback(new Error('输入正确手机号'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
  },

}
</script>